<template>
  <div>
    <div class="page-header">
      <h2>客户管理</h2>
      <div>
        <input type="file" accept=".xlsx" @change="importCustomers" style="display:none" ref="fileInput" />
        <button class="btn" @click="openAdd">新增客户</button>
        <button class="btn" @click="showImportDialog = true">导入</button>
        <button class="btn" @click="exportCustomers">导出</button>
        <input v-model="search" placeholder="搜索客户" class="search-input" />
      </div>
    </div>
    <!-- 依旧选择 -->
    <div v-if="showImportDialog" class="modal">
      <div class="modal-content">
        <h3>请选择导入方式</h3>
        <div style="margin: 20px 0;">
          <button class="btn" @click="handleDirectImport">直接导入</button>
          <button class="btn" @click="downloadTemplate">下载模板再导入（推荐）</button>
        </div>
        <button class="btn" @click="showImportDialog = false">取消</button>
      </div>
    </div>
    <table class="data-table">
      <thead>
        <tr>
          <th>客户名称</th>
          <th>联系方式</th>
          <th>邮箱</th>
          <th>地区</th>
          <th>操作</th>
        </tr>
      </thead>
<tbody>
  <tr v-for="item in filteredList" :key="item.id">
    <td>{{ item.name }}</td>
    <td>{{ item.phone }}</td>
    <td>{{ item.email }}</td>
    <td>{{ item.area }}</td>
    <td class="action-cell">
      <button class="btn" @click="edit(item)">编辑</button>
      <button class="btn" @click="removeCustomer(item.id)">删除</button>
    </td>
  </tr>
</tbody>
    </table>
    <div v-if="showAdd" class="modal">
      <div class="modal-content">
        <h3>{{ editId ? '编辑客户' : '新增客户' }}</h3>
        <input v-model="form.name" placeholder="客户名称" />
        <input v-model="form.phone" placeholder="联系方式" />
        <input v-model="form.email" placeholder="邮箱" />
        <input v-model="form.area" placeholder="地区" />
        <div class="modal-actions">
          <button class="btn" @click="save">保存</button>
          <button class="btn" @click="close">取消</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import * as XLSX from 'xlsx'
import axios from 'axios'
const list = ref([])
const search = ref('')
const showAdd = ref(false)
const editId = ref(null)
const form = ref({ name: '', phone: '', email: '', area: '' })
const fileInput = ref(null)
const showImportDialog = ref(false)

async function fetchList() {
  const res = await axios.get('http://localhost:8080/api/customers')
  list.value = res.data.map(item => ({
    name: item.customername,
    phone: item.customerphone,
    email: item.customeremail,
    area: item.customeraddress,
    id: item.customerid
  }))
}

onMounted(fetchList)

const filteredList = computed(() =>
  list.value.filter(item =>
    item.name.includes(search.value) ||
    item.phone.includes(search.value) ||
    item.email.includes(search.value) ||
    item.area.includes(search.value)
  )
)

function openAdd() {
  editId.value = null
  form.value = { name: '', phone: '', email: '', area: '' }
  showAdd.value = true
}
function edit(item) {
  editId.value = item.id
  form.value = { name: item.name, phone: item.phone, email: item.email, area: item.area }
  showAdd.value = true
}
async function removeCustomer(id) {
  try {
    await axios.delete(`http://localhost:8080/api/customers/${id}`);
    await fetchList();
  } catch (e) {
    alert(e.response?.data || '该客户有关联工单，不能被删除！');
  }
}
async function save() {
   if (form.value.phone && form.value.phone.length !== 11) {
    alert('电话号码位数错误，必须是11位！')
    return
  }
  const payload = {
    customername: form.value.name,
    customerphone: form.value.phone,
    customeremail: form.value.email,
    customeraddress: form.value.area
  }
  if (editId.value) {
    await axios.put(`http://localhost:8080/api/customers/${editId.value}`, payload)
  } else {
    await axios.post('http://localhost:8080/api/customers', payload)
  }
  await fetchList()
  close()
}
function close() {
  showAdd.value = false
  editId.value = null
  form.value = { name: '', phone: '', email: '', area: '' }
}
// 下边是要导出为Excel
function exportCustomers() {
  const header = ['客户名称', '联系方式', '邮箱', '地区'];
  const data = list.value.map(u => [u.name, u.phone, u.email, u.area]);
  const ws = XLSX.utils.aoa_to_sheet([header, ...data]);
  const wb = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(wb, ws, '客户数据');
  XLSX.writeFile(wb, '客户数据.xlsx');
}
// 文件选择
function triggerImport() {
  fileInput.value.click();
}
// 直接导入
function handleDirectImport() {
  showImportDialog.value = false;
  triggerImport();
}
// 弹窗中"下载模板"按钮
function downloadTemplate() {
  const header = ['客户名称', '联系方式', '邮箱', '地区'];
  const ws = XLSX.utils.aoa_to_sheet([header]);
  const wb = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(wb, ws, '客户模板');
  XLSX.writeFile(wb, '客户导入模板.xlsx');
}
// 导入Excel
async function importCustomers(e) {
  const file = e.target.files[0];
  if (!file) return;
  const reader = new FileReader();
  reader.onload = async function(evt) {
    const data = new Uint8Array(evt.target.result);
    const workbook = XLSX.read(data, { type: 'array' });
    const sheet = workbook.Sheets[workbook.SheetNames[0]];
    const rows = XLSX.utils.sheet_to_json(sheet, { header: 1 });
    const expectedHeader = ['客户名称', '联系方式', '邮箱', '地区'];
    const fileHeader = rows[0] || [];
    const isHeaderValid = expectedHeader.every((h, i) => h === fileHeader[i]);
    if (!isHeaderValid) {
      alert('导入失败：表头格式不正确，请使用模板或检查列顺序！');
      return;
    }
    const customers = rows.slice(1).map((row, idx) => {
      if (row.length < 4 || row.some(cell => cell === undefined || cell === null)) {
        alert(`第${idx + 2}行数据不完整，已跳过`);
        return null;
      }
      const phone = String(row[1] || '');
      if (phone && phone.length !== 11) {
        alert(`第${idx + 2}行电话号码位数错误，必须是11位！`);
        return null;
      }
      return {
        customername: row[0] || '',
        customerphone: row[1] || '',
        customerphone: phone,
        customeremail: row[2] || '',
        customeraddress: row[3] || ''
      };
    }).filter(Boolean);
    // 循环POST到后端
    for (const c of customers) {
      await axios.post('http://localhost:8080/api/customers', c);
    }
    // 导入后刷新列表
    await fetchList();
  };
  reader.readAsArrayBuffer(file);
}

</script>

<style scoped>
@import '../assets/style.css';
.page-header { display: flex; align-items: center; justify-content: space-between; margin-bottom: 16px; }
.data-table { width: 100%; border-collapse: collapse; background: #fff; }
.data-table th, .data-table td { border: 1px solid #eee; padding: 8px; }
.btn { background: #16a085; color: #fff; border: none; padding: 6px 16px; border-radius: 4px; cursor: pointer; margin-right: 8px; }
.search-input { padding: 6px 12px; border: 1px solid #ccc; border-radius: 4px; margin-top: 8px; }
.modal { position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.2); display: flex; align-items: center; justify-content: center; }
.modal-content { background: #fff; padding: 24px; border-radius: 8px; min-width: 300px; }
.modal-actions { margin-top: 16px; display: flex; gap: 12px; }
.action-cell { text-align: center; }
</style>